<?php

namespace Modules\Edu\Http\Controllers\Front;


use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
use Modules\Edu\Entities\Comment;
use Modules\Edu\Notifications\CommentMessageNotification;
use Modules\Edu\Transformers\CommentCollection;
use Modules\Edu\Transformers\CommentResource;

class CommentController extends Controller
{
//    public function __construct()
//    {
//        $this->middleware('auth')->only('store','destroy');
//    }

    public function index()
    {
        $comments = $this->model()->comments()->orderBy('id', 'asc')->get();
        return new CommentCollection($comments);
        //response()->json,会只提取data
//        return response()->json(['comments' => new CommentCollection($comments)]);
    }

    public function store(Request $request)
    {

        if (Auth::check()) {
            $model = $this->model();

            $comment = $model->comments()->create($request->input() +
                [
                    'site_id' => site()['id'],
                    'user_id' => user('id'),
                ]
            );
            $this->updateModelCount();
            //这里触发的是element的Message组件
            //传入前台$comment数据也需要CommentResource包裹。通过资源挂载user数据,否则前台报错没有user里得icon属性
            $this->notify($comment, $model);
            return response()->json(['message' => '评论发发表成功', 'comment' => new CommentResource($comment)]);
        }

        $url = $request->input('preUrl');
        session(['preUrl' => $url]);
        return route('login');

    }

//发送通知
    protected function notify($comment, $model)
    {
        if ($comment->user->id === $model->user->id) return;
        $title = '你收到了来自' . $model->user->name . '的评论';
        $action = $model->link;
        $model->user->notify(new CommentMessageNotification($title, $action));
    }

    public function destroy($model, $id, Comment $comment)
    {
        $comment->delete();
        $this->updateModelCount();
        return response()->json(['message' => '删除成功']);
    }

    protected function updateModelCount()
    {
        //
        $model = $this->model();
        $model->comment_count = $model->comments()->count();
        $model->save();
    }

    protected function model()
    {
        //根据模板名称在edu地址中找到对应模块并通过app()实例化
        $class = 'Modules\Edu\Entities\\' . request()->model;
        return app($class)->find(request()->id);
    }
}
